/**
 * Aurora 数据对象, 用于web/wap 公共端程序
 * 2017年12月26日 星期二
 */
import Util from './Util'
import {Config} from './Config'
import jutilStorage from './jutilStorage'
import {Think} from './Think'

// 全局变量
import LibBase64 from '../lib/Base64'
import WinValidate from './Validate'

// 系统全局变量
window.Base64 = LibBase64
window.Validate = WinValidate

// 局部全局变量
var _jsVar;

/**
 * aurora 系统抽象类
 */
class Aurora extends Util{
    constructor(){
        super()
        this._baseurl = Config.baseurl
        // 日志输出程序测试
        this.log = console.log
        // 数组类型判断
        this.is_array = Array.isArray
    }
    /**
     * 错误信息输出
     * @param {string} msg 
     */
    error(msg){
        throw new Error( "Syntax error, unrecognized expression(Conero): " + msg)
    }    
    /**
     * 
     * @param {*} engine 
     */
    storage(engine){
        return new jutilStorage(engine);
    }
    /**
     * 生成系统同全局的url
     * @param {string} url
     * @param {bool} suffix
     * @return {string}
     */
    getUrl(url, suffix){
        return this._baseurl + url + (suffix? '.html': '')
    }
    /**
     * 阿拉伯数组与英文对照
     * @param num int|string 数字
     * @param type 类型， sz/中文数字(默认), osz/繁体数字, dxq/短星期, xq/长星期
     * @return string
     */
    numberToZh(num, type){
        type = type? type.toLowerCase() : 'sz';
        var mapTb = [];
        switch(type){
            case 'osz':
                mapTb = ['零','壹','贰','叁','肆','伍','陆', '柒', '捌', '玖', '拾'];
                break;
            case 'dxq':
                mapTb = ['天','一','二','三','四','五','六'];
                break;
            case 'dxq':
                mapTb = ['星期天','星期一','星期二','星期三','星期四','星期五','星期六'];
                break;
            default:
                mapTb = ['零','一','二','三','四','五','六','七','八','九'];
        }
        if(num){
            if(!isNaN(num)){
                num = parseInt(num);
                if(num < 10) return mapTb[num]? mapTb[num]:'';
                else{
                    var tmpArr = (new String(num)).split('');
                    var str = '';
                    for(var i=0; i<tmpArr.length; i++){
                        var k = tmpArr[i];
                        str += mapTb[k]? mapTb[k]:'';
                    }
                    return str;
                }
            }
        }
        return '';
    }
    /**
     * 数字单位化
     * 1K => 千; 1M => 百万, 1G => 10亿
     * @param {number} num
     * @param {string|null} unit
     */
    numberUnited(num, unit){
        num = isNaN(num)? 0: num
        if(Math.abs(num) > 1000){
            num = num / 1000
            var que = ['K', 'M', 'G'],
                index = unit? $.inArray(unit, que) + 1 : -1
            unit = index > -1? que[index]: 'K'
            return this.numberUnited(num, unit)
        }else{
            try {
                num = num.toFixed(2)
            } catch (error) {
                console.log(error)
            }
            num = num + (unit? unit: '')
        }
        return num
    }
    /**
     * 计算总列数 - 2017年7月4日 星期二     
     * @param count int 总数据列
     * @param num int 单页显示的列数 = 20
     * @return int 总页数
     */
    getAllPage(count, num){
        num = isNaN(num)? 20 : parseInt(num);
        count = isNaN(count)? 0 : parseInt(count);
        if(0 === count) return count;
        else if(count <= num) return 1;
        return Math.ceil(count/num);
    }

    // PHP+js+Base64    
    getJsVar(key){
		if(typeof AuroarJs == 'undefined') return '';// undefind 函数无效
		if(this.empty(AuroarJs)) return '';
        if(this.is_string(AuroarJs) && !this.is_object(_jsVar)){
            _jsVar = JSON.parse(Base64.decode(AuroarJs));
        }
        if(this.is_object(_jsVar)){
			if(this.undefind(key)) return _jsVar;
            if(this.empty(_jsVar[key])) return '';
            return _jsVar[key];
        }
		return '';
    }

    // 与 php bsjson 函数匹配
	bsjson(value){
		if(value){
			// 解密并返回 对象
			if(this.is_string(value)){
				try {
					value = Base64.decode(value);
					return JSON.parse(value);
				} catch (error) {
					this.error(error);
				}
			}
			else if(this.is_object(value) && this.objectLength(value) >0){
				var str = JSON.stringify(value);
				return Base64.encode(str);
			}
		}
		return '';
	}

    // getUrlBind - 对应PHP版函数 -- $name=null,$ogri=false,$position='LEFT'
	getUrlBind(name,ogri,position){
		position = position? 'RIGHT':'LEFT';
		var path = location.pathname;
		var data = path.split('/');
		var ret, index;
		if(name){
			for(var i=0; i<data.length; i++){
				if(name == data[i]){
					index = (position == 'LEFT')? (i+1):(i-1);
					if(index >= 0 && index < data.length){
						ret = data[index];
						if(!ogri){
							var reg = /(\.shtml)|(\.html)|(\.htm)/;
							ret = ret.replace(reg,'');
						}						
					}
					else ret = '';
					return ret;
				}
			}
			return '';
		}
		else ret = name;
		return ret;
    }

    /**
     * 前端 api 简单封装
     * @param {string} url
     * @param {object|null} data
     * @param {function} func
     * @constructor
     */
    ApiRequest(url,data,func) {
        url = this.ApiUrl(url);
        $.ajax({
            type: 'post',
            url,
            timeout: 3000,
            data: data,
            success: func,
            err: function(xhr, type){
                func({code: -1, msg:'网络请求失败，请检查网络或者联系网络联系人!'});
            }
        });

        // 网络请求超时处理 weui.loading 框
        // 关闭存在的 weui
        if(Config.AjaxTimeout && this.weuiLoading){
            let instance = this;
            let sec = Config.AjaxTimeout * 60 * 1000;
            setTimeout(function () {
                instance.weuiLoading();
                weui.topTips('页面操作超时，请稍后重试！', sec);
            }, sec);
        }
    }
    /**
     * @param {string} url
     * @returns {string}
     */
    ApiUrl(url){
        return this._baseurl + 'api/'+url;
    }

    /**
     * 表单重置
     * @param selector string|jquery
     * @param ignore    []string|string
     * @constructor
     */
    ResetForm(selector,ignore) {
        selector = selector? selector:'body';
        var el = typeof selector == 'object'? selector:$(selector);
        ignore = ignore? ignore: [];
        ignore = typeof ignore == 'object'? ignore:[ignore];
        var ipts = el.find('input');
        for(var i=0; i<ipts.length; i++){
            var ipt = $(ipts[i]);
            if(typeof ipt.attr('disabled') != 'undefined') continue;
            if(ignore.length>0){
                var iptName = ipt.attr("name");
                if(iptName && $.inArray(iptName,ignore)>-1) continue;
            }
            var iptType = ipt.attr('type');
            if(iptType == 'checkbox' || iptType == 'radio'){ // 暂时无法重置
                if(el.is('checked')) el.attr('checked',false);
                continue;
            }
            ipt.val('');
        }
        var textareas = el.find('textarea');
        for(var j=0; j<textareas.length; j++){
            var textarea = $(textareas[j]);
            if(ignore.length>0){
                var txtName = textarea.attr("name");
                if(txtName && $.inArray(txtName,ignore)>-1) continue;
            }
            textarea.val('');
        }
        var selects = el.find('select');
        for(var x=0; x<selects.length; x++){
            var sel = $(selects[x]);
            if(ignore.length>0){
                var selName = sel.attr("name");
                if(selName && $.inArray(selName,ignore)>-1) continue;
            }
            if(sel.find('option:selected').length>0) sel.find('option:selected').attr('selected',false);
        }
    }
    /**
     * 获取控制器相关名称
     * @param key
     * @returns {*}
     * @constructor
     */
    Think() {
        return new Think(this)
    }
    /**
     * 对象扩展，将object添加为自己的方法
     * @param {object} object 
     */
    Extends(object){
        if('object' == typeof object){
            for(var key in object){
                this[key] = object[key]
            }
            return true
        }
        return false;
    }

    /**
     * 自动完成
     * @param {string} selector
     * @param {string} ctrl
     * @param {int|null} limit
     */
    autocomplete(selector, ctrl, limit){
        var id = ('string' === typeof selector)? Base64.encode(selector): Base64.encode(ctrl);
        id = `ds_${id}_ctrl`;
        id = id.replace(/[+=-]/g, '');
        selector = 'object' === typeof selector? selector : $(selector);
        var cacheValue = null;
        // keydown 请求次数太多
        // change 单次
        selector.keydown(function () {
            var ipt = $(this);
            var name = ipt.val();
            if(name === cacheValue || !name){
                return;
            }

            cacheValue = name;
            $.post('/api/aurora/autocomplete', {controller: ctrl, name: name, limit: limit || null}, function (rs) {
                let values = rs.data || null;
                values = values? values.values : null;
                if(values && 'object' === typeof values && values.length > 0){
                    let ds = $(`#${id}`);
                    if(ds.length < 1){
                        ipt.after(`<datalist id="${id}"></datalist>`);
                        ds = $(`#${id}`);
                    }else {
                        ds.html('');
                    }
                    for(let i=0; i<values.length; i++){
                        ds.append(`<option value="${values[i]}"/>`);
                    }
                    ipt.attr('list', id);
                }
            });
        });
    }
}

export {Aurora}